package com.elitel.common.auth.filter;

import com.alibaba.fastjson.JSON;
import com.elitel.common.auth.AuthProperties;
import com.elitel.common.auth.service.SysUserService;
import com.elitel.common.core.constant.SysUserConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 用户过滤器
 * @author mulis
 */
@Component
@ConditionalOnProperty(prefix = "auth.login-user-filter", name = "enabled", havingValue = "true")
@WebFilter(urlPatterns = "/*")
public class SysUserFilter implements Filter, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(SysUserFilter.class);

    @Resource
    private AuthProperties authProperties;

    @Resource
    private SysUserService userService;



    // 匹配路径工具类
    private Pattern pattern;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化匹配路径工具类
        pattern = Pattern.compile(authProperties.getRegExcludeUrl());
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 非拦截路径 不拦截
        if (pattern.matcher(request.getRequestURI()).find()) {
            logger.debug("Request is ignored.");
            filterChain.doFilter(request, response);
            return;
        }

        // 不是接口请求 不拦截
        if (!"XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {
            filterChain.doFilter(request, response);
            return;
        }

        boolean isWhitelist = userService.userExist();

        // 是白名单用户 不拦截
        if (isWhitelist) {
            filterChain.doFilter(request, response);
            return;
        }

        // 不是白名单用户 就直接响应4021未授权 不执行应用逻辑
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> resultMap = new HashMap<>(3);
        resultMap.put("code", 4021);
        resultMap.put("success", false);
        resultMap.put("msg", "访问受限，请联系管理员");
        out.write(JSON.toJSONString(resultMap));
        out.flush();
        out.close();
    }

    @Override
    public void destroy() {

    }

    @Override
    public int getOrder() {
        return 5;
    }
}
